package net.threeple.springjdbc.helper;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.util.StringUtils;

import com.google.common.base.CharMatcher;
import com.google.common.collect.Maps;

public class NamedQueryStore {
	static final Logger logger = LoggerFactory.getLogger(NamedQueryStore.class);
	
	private Map<String, String> queries = Maps.newHashMap();
	
	public NamedQueryStore(String filepath) {
		Resource resource = new ClassPathResource(filepath);
		if(resource.exists()) {
			
			try {
				BufferedReader br = new BufferedReader(new InputStreamReader(resource.getInputStream(), StandardCharsets.UTF_8));
				String line = "";
				String key = "", value = "";
				while((line = br.readLine()) != null) {
					line = line.trim();
					if(line.matches("^\\[\\w+\\]$")) {
						if(StringUtils.hasText(key) 
								&& StringUtils.hasText(value)) {
							queries.put(key, CharMatcher.WHITESPACE.trimAndCollapseFrom(value, ' '));
							logger.debug("命名查询【{}】：{}", key, value);
							key = "";
							value = "";
						}
						key = line.substring(1, (line.length() - 1));
					} else {
						value = value + line + " ";
					}
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		} else {
			logger.error("命名查询文件【{}】不存在。", filepath);
		}
	}
	
	public String get(String name) {
		return queries.get(name);
	}
}
